from django.views import View
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from tortoise import Tortoise
from tortoise.exceptions import DoesNotExist
from .models import User
from django.conf import settings
from asgiref.sync import async_to_sync
import json


# 全局标志变量，控制数据库初始化是否执行过
db_initialized = False

# 初始化数据库连接
async def init_db():
    global db_initialized

    if db_initialized:
        return  # 如果已经初始化，直接返回
    tortoise_config = settings.TORTOISE_ORM

    await Tortoise.init(
        db_url=tortoise_config['connections']['default'],
        modules={'models': ['framework_core.models']}
    )
    await Tortoise.generate_schemas(safe=True)
    db_initialized = True  # 设置标志，表示数据库已经初始化过了


class UserView(View):
    @method_decorator(async_to_sync) 
    @method_decorator(csrf_exempt)
    async def dispatch(self, request, *args, **kwargs):
        await init_db()
        return await super().dispatch(request, *args, **kwargs)

    # 列出所有 User（GET）
    async def get(self, request, *args, **kwargs):
        # 如果传递了 'pk' 参数（即获取单个用户）
        pk = kwargs.get('pk', None)
        if pk is not None:
            # 获取单个用户
            user = await User.get_or_none(id=pk)

            if user:
                return JsonResponse({"id": user.id, "name": user.name}, status=200)

            return JsonResponse([], safe=False, status=404)

        users = await User.all()  # 查询所有用户
        user_list = [{"id": u.id, "name": u.name} for u in users]
        return JsonResponse(user_list, safe=False, status=200)

    # 创建 User（POST）
    async def post(self, request, *args, **kwargs):
        name = request.POST.get("name")
        if name:
            user = await User.create(name=name)
            return JsonResponse({'id': user.id, 'name': user.name}, status=201)

        return JsonResponse({'error': 'Name is required'}, status=400)

    # 修改 User（PUT）
    async def put(self, request, pk, *args, **kwargs):
        user = await User.get_or_none(id=pk)
        if user:
            data = json.loads(request.body)
            user.name = data.get('name', user.name)
            await user.save()
            return JsonResponse({'id': user.id, 'name': user.name}, status=200)

        return JsonResponse({'error': 'User not found'}, status=404)

    # 删除 User（DELETE）
    async def delete(self, request, pk, *args, **kwargs):
        user = await User.get_or_none(id=pk)
        if user:
            await user.delete()
            return JsonResponse({'message': 'User deleted successfully'}, status=200)

        return JsonResponse({'error': 'User not found'}, status=404)


